import React, {useEffect, useState} from 'react'
import {Form, Button, DatePicker, Input, Modal, Select, Row, Col, Upload, message, InputNumber, Table, TreeSelect} from 'antd'
import {UploadOutlined, SearchOutlined} from '@ant-design/icons';
import {getUploadUrl} from "@/utils/upload";
import moment from 'moment'
import {connect} from 'umi'
import SelectUserModal from "@/pages/components/SelectUserModal";
import {getJobByOrgId} from "../service";
import {findItemByTree} from "@/utils/functions";
import {getComputerSubsidyByOid} from "@/pages/Personnel/Transfer/service";
import {applyMannerList} from "@/utils/constant";

const FormItem = Form.Item;
const Option = Select.Option;
const {TextArea} = Input;

const formLayout = {
  labelCol: {span: 7},
};
const colStyle = {
  xl: 12,
  lg: 12,
  md: 12,
  sm: 12,
  xs: 12,
};

let uploadedFiles = [];

const CreateForm = (props) => {
  const {onSubmit, onCancel, loading, record, visible, global = {}} = props;
  const {options = {}} = global;
  const {orgTree = []} = options;
  const [fileName, setFileName] = useState(null);
  const [fileUploadUrls, setFileUploadUrls] = useState([]);
  const [formTitle, setFormTitle] = useState('新增借调');
  const [beforeInfo, setBeforeInfo] = useState(null);
  const [form] = Form.useForm();
  const [orgList, setOrgList] = useState([]);
  const [userModalVisible, setUserModalVisible] = useState(false);
  const [unitTree, setUnitTree] = useState([]);
  const [jobList, setJobList] = useState([]);
  const [isDisabled, setIsDisabled] = useState(false);
  const [showAdjustmentSubsidy, setShowAdjustmentSubsidy] = useState(false);
  const [dataSource, setDataSource] = useState([]);
  const [fileList, setFileList] = useState([]);

  const fileProps = {
    name: 'file',
    multiple: false,
    action: getUploadUrl(),
    defaultFileList: uploadedFiles,
    data: {name: fileName},
    fileList: fileList,
    beforeUpload(file) {
      if (file.size/1024 > 10000) {
        message.error(`上传文件大小不能超过10M！`);
        return false;
      }
      setFileName(file.name)
    },
    onChange(info) {
      const {status} = info.file;
      if (status === 'done') {
        if (info.file.response.error) {
          message.success(`${info.file.response.error} 。`);
        } else {
          let urls = fileUploadUrls;
          urls.push(info.file.response);
          setFileUploadUrls(urls);
          message.success(`${info.file.name} 文件上传成功。`);
        }
      } else if (status === 'error') {
        message.error(`${info.file.name} 文件上传失败。`);
      }
      let files = info.fileList.filter(item => item.status);
      setFileList(files);
    },
    onRemove(info) {
      let urls = fileUploadUrls;
      let index = urls.indexOf(info.url);
      if (index > -1)
        urls.splice(index, 1);
      setFileUploadUrls(urls);
    }
  };

  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
    },
    {
      title: '申请方式',
      dataIndex: 'applyMode',
      render: (text) => text && applyMannerList.find(item => item.value = text).label
    },
    {
      title: '申请时间',
      dataIndex: 'applyDate',
      render: (text) => text && moment(text).format('YYYY-MM-DD')
    },
    {
      title: '申请总金额',
      dataIndex: 'duration',
      render: (text, record) => (text ? parseInt(text) * parseInt(record.monthlyAmount).toFixed(2) : 0)
    },
    {
      title: '每月金额',
      dataIndex: 'monthlyAmount',
    },
    {
      title: '补贴开始时间',
      dataIndex: 'startDate',
      render: (text) => text && moment(text).format('YYYY-MM-DD')
    },
    {
      title: '补贴结束时间',
      dataIndex: 'endDate',
      render: (text) => text && moment(text).format('YYYY-MM-DD')
    },
  ];

  useEffect(() => {
    if (visible) {
      let temp = [];
      orgTree.map((item, index) => {
        temp.push({title: item.title, value: item.value, key: index})
      });
      setOrgList(temp);
    }
    if (record) {
      if (record.type === 'end') {
        setIsDisabled(true);
      }
      setFormTitle('编辑借调');
      let orgId = parseInt(record.secondmentOrgId);
      onChangeOrgId(orgId);
      let unitId = parseInt(record.secondmentUnitId);
      onChangeUnitId(unitId);
      let isAdjustmentSubsidy = 0;
      if (record.beforeSubsidyId) {
        setShowAdjustmentSubsidy(true);
        isAdjustmentSubsidy = 1;
        getComputerSubsidyByOid(record.oid).then(res => {
          setDataSource(res.data);
        });
      }
      form.setFieldsValue({
        ...record,
        isAdjustmentSubsidy,
        orgname: record.orgName,
        unitname: record.unitName,
        jobname: record.jobName,
        secondmentOrgId: orgId,
        secondmentUnitId: unitId,
        outTime: moment(record.outTime),
        expectedEndTime: moment(record.expectedEndTime),
        endTime: record.endTime && moment(record.endTime),
        beforeSubsidyEnd: record.beforeSubsidyEnd && moment(record.beforeSubsidyEnd),
        afterSubsidyEnd: record.afterSubsidyEnd && moment(record.afterSubsidyEnd),
        afterSubsidyStart: record.afterSubsidyStart && moment(record.afterSubsidyStart)
      });
      if (record.fileUrl) {
        let fileUrlList = record.fileUrl.split(',');
        setFileUploadUrls(fileUrlList);
        fileUrlList.forEach((item, index) => {
          uploadedFiles.push({
            uid: index,
            name: item.split('----')[1],
            status: 'done',
            url: item,
          })
        })
      }
      setBeforeInfo(record);
    } else {
      setFormTitle('新增借调');
    }
  }, [visible]);

  const onFormCancel = () => {
    uploadedFiles = [];
    setFileUploadUrls([]);
    form.resetFields();
    setBeforeInfo(null);
    onCancel();
    setIsDisabled(false);
  };

  const handleSubmit = async () => {
    const fieldsValue = await form.validateFields();
    if (!showAdjustmentSubsidy) {
      fieldsValue.beforeSubsidyEnd = '';
      fieldsValue.beforeSubsidy = '';
      fieldsValue.beforeSubsidyId = '';
      fieldsValue.afterSubsidyEnd = '';
      fieldsValue.afterSubsidyStart = '';
      fieldsValue.afterSubsidy = '';
    }
    onSubmit({
      ...fieldsValue,
      oid: beforeInfo.oid,
      code: beforeInfo.code,
      orgId: beforeInfo.orgId,
      unitId: beforeInfo.unitId,
      jobId: beforeInfo.jobId,
      fileUrlList: fileUploadUrls,
      id: record && record.id,
      status: record && record.type === 'end' ? 4 : 0
    });
    form.resetFields();
    setBeforeInfo(null);
    setFileUploadUrls([]);
    uploadedFiles = [];
    setIsDisabled(false);
  };

  const showSelectUserModal = () => {
    setUserModalVisible(true);
  };

  const confirmSelectUser = (info) => {
    if (info) {
      setBeforeInfo(info[0]);
      form.setFieldsValue({
        name: info[0].name,
        orgname: info[0].orgname,
        unitname: info[0].unitname,
        jobname: info[0].jobname
      });
      setUserModalVisible(false);
    } else {
      message.error('请选择人员!')
    }
  };

  const filterOption = (input, option) => {
    return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
  };

  const cancelSelectUser = () => {
    setUserModalVisible(false);
  };

  const onChangeOrgId = (e) => {
    form.setFieldsValue({secondmentUnitId: null, secondmentJobId: null});
    const item = findItemByTree(orgTree, e);
    setUnitTree(item ? item.children : []);
  };

  const onChangeUnitId = (e) => {
    form.setFieldsValue({secondmentJobId: null});
    getJobByOrgId(e).then((res) => {
      setJobList(res);
    })
  };

  const isShowSubsidyInfo = (value) => {
    setShowAdjustmentSubsidy(value);
    if (value) {
      let restSubsidyInfo = record ?
        {
          beforeSubsidyEnd: record.beforeSubsidyEnd ? moment(record.beforeSubsidyEnd) : null,
          afterSubsidyEnd: record.afterSubsidyEnd ? moment(record.afterSubsidyEnd) : null,
          afterSubsidyStart: record.afterSubsidyStart ? moment(record.afterSubsidyStart) : null,
          afterSubsidy: record.afterSubsidy ? record.afterSubsidy : null
        } : {};
      getComputerSubsidyByOid(beforeInfo.oid).then(res => {
        setDataSource(res.data);
        if (res.data.length > 0)
          form.setFieldsValue({
            ...restSubsidyInfo,
            beforeSubsidyEnd: moment(res.data[0].endDate),
            beforeSubsidy:  res.data[0].monthlyAmount,
            beforeSubsidyId: res.data[0].id,
          })
      });
    } else {
      setDataSource([]);
      form.setFieldsValue({
        beforeSubsidyEnd: null,
        beforeSubsidy: null,
        beforeSubsidyId: null,
        afterSubsidyEnd: null,
        afterSubsidyStart: null,
        afterSubsidy: null
      })
    }
  };

  const renderContent = () => {
    return (<>
      <Row gutter={24}>
        <Col {...colStyle}>
          <FormItem name="name" label="借调人员" rules={[{required: true, message: '借调人员不能为空'}]}>
            <Input.Group compact size="large">
              <Input style={{width: '80%', background: '#fff', height: '32px', fontSize: '14px'}} placeholder="选择借调人员"
                     value={beforeInfo ? beforeInfo.name : record && record.name} disabled={true}/>
              <Button style={{width: '20%'}} disabled={isDisabled} icon={<SearchOutlined/>}
                      onClick={() => showSelectUserModal()}/>
            </Input.Group>
          </FormItem>
        </Col>
        <Col {...colStyle}>
          <FormItem name="orgname" label="原公司" rules={[{required: true, message: '原公司不能为空'}]}>
            <Input disabled={true}/>
          </FormItem>
        </Col>
        <Col {...colStyle}>
          <FormItem name="unitname" label="原部门" rules={[{required: true, message: '原部门不能为空'}]}>
            <Input disabled={true}/>
          </FormItem>
        </Col>
        <Col {...colStyle}>
          <FormItem name="jobname" label="原岗位" rules={[{required: true, message: '原岗位不能为空'}]}>
            <Input disabled={true}/>
          </FormItem>
        </Col>

        <Col {...colStyle}>
          <FormItem name="secondmentOrgId" label="借调公司" rules={[{required: true, message: '借调公司不能为空'}]}>
            <TreeSelect treeData={orgTree} onChange={onChangeOrgId}/>
          </FormItem>
        </Col>

        <Col {...colStyle}>
          <FormItem name="secondmentUnitId" label="借调部门" rules={[{required: true, message: '借调部门不能为空'}]}>
            <TreeSelect disabled={isDisabled} treeData={unitTree} onChange={onChangeUnitId}/>
          </FormItem>
        </Col>
        <Col {...colStyle}>
          <FormItem name="secondmentJobId" label="借调岗位" rules={[{required: true, message: '借调岗位不能为空'}]}>
            <Select disabled={isDisabled} placeholder="请选择" showSearch filterOption={filterOption}>
              {jobList.map((item, index) => {
                return (
                  <Option value={`${item.coidassignedjob}`} key={item.coidassignedjob}>
                    {item.cname}
                  </Option>
                )
              })}
            </Select>
          </FormItem>
        </Col>
        <Col {...colStyle}>
          <FormItem name="outTime" label="调出日期" rules={[{required: true, message: '调出日期不能为空'}]}>
            <DatePicker disabled={isDisabled} className='widthStyle'/>
          </FormItem>
        </Col>
        <Col {...colStyle}>
          <FormItem name="expectedEndTime" label="预计结束日期" rules={[{required: true, message: '预计结束日期不能为空'}]}>
            <DatePicker disabled={isDisabled} className='widthStyle'/>
          </FormItem>
        </Col>
        <Col {...colStyle}>
          <FormItem name="proportion" label="调入部门承担比例" rules={[{required: true, message: '成本比例不能为空！'}]}>
            <Input disabled={isDisabled} placeholder='请输入调入部门承担成本比例' suffix="%"/>
          </FormItem>
        </Col>
        {/*<Col {...colStyle}>
          <FormItem name="subsidy" label="异地补贴" rules={[{required: true, message: '异地补贴不能为空！'}, ({
            validator(rule, value) {
              let pattern = /(^[1-9]([0-9]*)$|^[0-9]$)/;
              if (pattern.test(value)) {
                return Promise.resolve();
              }
              return Promise.reject('请输入数字类型的正确金额');
            },
          })]}>
            <Input disabled={isDisabled} suffix="元"/>
          </FormItem>
        </Col>*/}
        <Col {...colStyle}>
          <FormItem labelCol={{span: 8}} name="isAdjustmentSubsidy" label="是否调整补贴">
            <Select disabled={!beforeInfo} defaultValue={0} placeholder="请选择" showSearch filterOption={filterOption}
                    onChange={isShowSubsidyInfo}>
              <Option value={0}>否</Option>
              <Option value={1}>是</Option>
            </Select>
          </FormItem>
        </Col>
        {
          showAdjustmentSubsidy ?
            <Col span={24}>
              <Row gutter={24}>
                {
                  dataSource.length > 0 &&
                  <>
                    <Col span={24} style={{marginBottom: 15}}>
                      <Table rowKey='id' dataSource={dataSource} pagination={false} columns={columns}/>
                    </Col>
                    <Col {...colStyle}>
                      <FormItem labelCol={{span: 7}} name="beforeSubsidyEnd" label="原补贴结束时间"
                                rules={[{required: true, message: '原补贴结束时间不能为空'}]}>
                        <DatePicker className='widthStyle'/>
                      </FormItem>
                    </Col>
                    <Col span={0}>
                      <FormItem name="beforeSubsidy" label="原补金额">
                        <InputNumber/>
                      </FormItem>
                    </Col>
                    <Col span={0}>
                      <FormItem name="beforeSubsidyId" label="原补id">
                        <Input/>
                      </FormItem>
                    </Col>
                  </>
                }
                <Col {...colStyle}>
                  <FormItem labelCol={{span: 7}} name="afterSubsidy" label="调整后每月补贴金额"
                            rules={[{required: true, message: '调整后每月补贴金额不能为空'}]}>
                    <InputNumber style={{width: '100%'}} className='widthStyle' min={0}/>
                  </FormItem>
                </Col>
                <Col {...colStyle}>
                  <FormItem labelCol={{span: 7}} name="afterSubsidyStart" label="补贴开始时间"
                            rules={[{required: true, message: '原补贴开始时间不能为空'}]}>
                    <DatePicker className='widthStyle'/>
                  </FormItem>
                </Col>
                <Col {...colStyle}>
                  <FormItem labelCol={{span: 7}} name="afterSubsidyEnd" label="补贴结束时间"
                            rules={[{required: true, message: '原补贴结束时间不能为空'}]}>
                    <DatePicker className='widthStyle'/>
                  </FormItem>
                </Col>
              </Row>
            </Col> : ''
        }


        <Col span={record && record.type === 'end' ? 0 : 12}>
          <FormItem label="附件上传">
            <Upload disabled={isDisabled} {...fileProps}>
              <Button>
                <UploadOutlined/> 点击上传附件
              </Button>
            </Upload>
          </FormItem>
        </Col>
        <Col span={record && record.type === 'end' ? 12 : 0}>
          <FormItem name="endTime" label="实际结束日期"
                    rules={record && record.type === 'end' ? [{required: true, message: '实际结束日期不能为空'}] : ''}>
            <DatePicker className='widthStyle'/>
          </FormItem>
        </Col>
        <Col span={24}>
          <FormItem name="reason" labelCol={{span: 2}} label="借调原因" rules={[{required: true, message: '借调原因不能为空！'}]}>
            <TextArea disabled={isDisabled} placeholder="请输入借调原因" rows={8} className='widthStyle'/>
          </FormItem>
        </Col>
      </Row>
    </>)
  };

  const renderFooter = () => {
    return (
      <>
        <Button onClick={() => onFormCancel()}>关闭页面</Button>
        <Button type="primary" loading={loading} onClick={() => handleSubmit()}>保存</Button>
      </>
    )
  };

  return (
    <Modal
      width={'60%'}
      destroyOnClose
      title={formTitle}
      visible={visible}
      footer={renderFooter()}
      onOk={handleSubmit}
      onCancel={() => onFormCancel()}
      okText="确认"
      cancelText="取消"
    >
      <Form
        {...formLayout}
        form={form}
      >
        {renderContent()}
      </Form>
      <SelectUserModal
        selectType={0}
        visible={userModalVisible}
        handleOk={confirmSelectUser}
        handleCancel={cancelSelectUser}
      />
    </Modal>
  )
};

export default connect(({user, global}) => ({
  currentUser: user.currentUser,
  global
}))(CreateForm)
